import { ajax, serverUrl } from '../lib/ajax.js';
import { tools } from '../lib/tools.js';

console.log('格式化时间测试：', tools.formatDate(new Date()));
console.log('格式化时间测试：', tools.formatDate(new Date(), 'yyyy-MM-dd'));
console.log('格式化时间测试：', tools.formatDate(new Date(), 'hh时mm分ss秒'));

let divUser = document.getElementById('divUser');
let divNoUser = document.getElementById('divNoUser');

divUser.style.display = 'none';

let img_avatar = document.getElementById('img_avatar');
let divUserInfo = document.getElementById('divUserInfo');
let btnLogout = document.getElementById('btnLogout');

btnLogout.addEventListener('click', () => {
  ajax.delete('/auth', {}, () => {
    location.href = 'login.html';
  });
});

// 获取用户是否登录
function queryUser() {
  ajax.get('/auth', {}, (data) => {
    console.log('登录信息：', data);
    if (data.success) {
      divUser.style.display = 'block';
      divNoUser.style.display = 'none';
      showUserInfo(data);
      showUserAvatar(data);
    }
  });
}

// 显示用户信息
function showUserInfo(data) {
  let user = data.data.tbUser;
  let userinfo = data.data.tbUserInfo;
  if(userinfo.sex=='m'){
    userinfo.sex = '男生';
} else if(userinfo.sex== 'f') {
  userinfo.sex ='女生';
} else if(userinfo.sex== 'n') {
  userinfo.sex = '保密'；
}
  
  divUserInfo.innerHTML = `
    ${user.username}(${userinfo.sex})-${userinfo.nickname}
    -注册时间：${tools.formatDate(user.lastupdate, 'yyyy-MM-dd')}
    <br>
    ${userinfo.sex}
  `;
}
// 显示用户头像
function showUserAvatar(data) {
  img_avatar.setAttribute(
    'src',
    serverUrl + '/user/logo/' + data.data.tbUser.uid
  );
}
queryUser();
